//
//  CredibilityViewController.m
//  Logistics
//
//  Created by hy002 on 2018/1/12.
//  Copyright © 2018年 HUYU. All rights reserved.
//

#import "CredibilityViewController.h"
#import "CommentOfMineViewController.h"
#import "CDZStarsControl.h"
#import "GoodsAddressModel.h"
#import "DetailsModel.h"
#import "CommentModel.h"
#import "IndustrialViewController.h"

static NSString *cellPath = @"CredibilityCell";
@interface CredibilityViewController ()<UITableViewDelegate,UITableViewDataSource,CDZStarsControlDelegate>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *typeAry;
@property (nonatomic, strong)NSMutableArray *allcommentAry;
@property (nonatomic, assign)BOOL isGx;
@property (nonatomic, strong)DetailsModel *detaModel;
@property (nonatomic, assign)NSInteger page;

@end

@implementation CredibilityViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _page = 0;
    [self requestComment];
    [self requestCompanySelect];
    [self requestCommentList];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 0;
    _allcommentAry = [NSMutableArray arrayWithCapacity:0];
    [self creatUI];
    
}

- (void)creatUI
{
    self.navigationItem.title = @"综合信誉";
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-65*displaywidth) style:UITableViewStylePlain];
    _tableview.backgroundColor = BacksColor;
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    self.tableview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.tableview.mj_footer.automaticallyHidden = YES;
    self.tableview.estimatedRowHeight = 0;
    self.tableview.estimatedSectionHeaderHeight = 0;
    self.tableview.estimatedSectionFooterHeight = 0;
    UIButton *soureBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth, SCREEN_HEIGHT-STA_NAV_HEIGHT-SCREER_HeiX-55*displaywidth, SCREEN_WIDTH-30*displaywidth, 45*displaywidth) ImageName:nil Target:self Action:@selector(soureBtnAction) Title:@"我要评论" Font:16.0];
    soureBtn.backgroundColor = RGB(255, 153, 0);
    [soureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    soureBtn.layer.cornerRadius = 5;
    soureBtn.layer.masksToBounds = YES;
    [self.view addSubview:soureBtn];
}

- (void)loadNewHeaderData
{
    _page = 0;
    [self requestCommentList];
    
}

- (void)loadMoreFootData
{
    _page ++;
    [self requestCommentList];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 1)
    {
        return _allcommentAry.count;
    }
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            UIImageView *imgAview = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 7.5*displaywidth, 45*displaywidth, 30*displaywidth) ImageName:@""];
            if (![_detaModel.logo isEqualToString:@""])
            {
                [imgAview sd_setImageWithURL:URL(_detaModel.logo)];
            }
            imgAview.contentMode = UIViewContentModeScaleAspectFill;
            imgAview.layer.masksToBounds = YES;
            [cell.contentView addSubview:imgAview];
            UILabel *namelab = [ZCControl createLabelWithFrame:CGRectMake(75*displaywidth, 5*displaywidth, SCREEN_WIDTH-90*displaywidth, 35*displaywidth) Font:15.0 Text:_detaModel.companyName Color:BlaTitColor];
            [cell.contentView addSubview:namelab];
            UIView *lineAview = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, 45*displaywidth, SCREEN_WIDTH-30*displaywidth, 1)];
            lineAview.backgroundColor = LinesColor;
            [cell.contentView addSubview:lineAview];
            CDZStarsControl *starsControl = [[CDZStarsControl alloc] initWithFrame:CGRectMake(140*displaywidth, 80*displaywidth, 200*displaywidth , 45*displaywidth) stars:5 starSize:CGSizeMake(40*displaywidth, 40*displaywidth) noramlStarImage:[UIImage imageNamed:@"star_normal"] highlightedStarImage:[UIImage imageNamed:@"star01"]];
            starsControl.delegate = self;
            starsControl.allowFraction = YES;
            starsControl.score = [_detaModel.avgRate floatValue];
            starsControl.isEntlab = NO;
            [cell.contentView addSubview:starsControl];
            UILabel *numLab = [ZCControl createLabelWithFrame:CGRectMake(35*displaywidth, 45*displaywidth, 70*displaywidth, 105*displaywidth) Font:12.0 Text:[NSString stringWithFormat:@"%@\n综合信誉",_detaModel.avgRate] Color:RGB(153, 153, 153)];
            numLab.textAlignment = NSTextAlignmentCenter;
            NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n综合信誉",_detaModel.avgRate]];
            NSRange titleRange = [[title string]rangeOfString:[NSString stringWithFormat:@"%@",_detaModel.avgRate]];
            [title addAttribute:NSForegroundColorAttributeName value:RGB(255, 51, 51) range:titleRange];
            [title addAttribute:NSFontAttributeName value:NormalFontWithSize(31.0+fontScale) range:titleRange];
            numLab.attributedText = title;
            [cell.contentView addSubview:numLab];
            UIView *lineDview = [[UIView alloc] initWithFrame:CGRectMake(120*displaywidth, 80*displaywidth, 1*displaywidth, 45*displaywidth)];
            lineDview.backgroundColor = RGB(204, 204, 204);
            [cell.contentView addSubview:lineDview];
            
        }
        else if (indexPath.row == 2)
        {
            UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10*displaywidth)];
            lineBview.backgroundColor = BacksColor;
            [cell.contentView addSubview:lineBview];
            if (_typeAry.count > 0)
            {
                CGFloat h2 = 25*displaywidth;
                CGFloat w2 = 0;
                CGFloat width = SCREEN_WIDTH;
                for (int i = 0; i < _typeAry.count; i++)
                {
                    GoodsAddressModel *sizeModel = _typeAry[i];
                    NSString *typename = [NSString stringWithFormat:@"%@(%@)",sizeModel.name,sizeModel.count];
                    UIButton *tasteBtn = [ZCControl createButtonWithFrame:CGRectMake(15*displaywidth+i*75*displaywidth, h2, 60*displaywidth, 25*displaywidth) ImageName:nil Target:nil Action:nil Title:typename Font:12.0];
                    tasteBtn.tag = 500+i;
                    NSDictionary *attributes = @{NSFontAttributeName:NormalFontWithSize(12.0+fontScale)};
                    CGFloat length = [typename boundingRectWithSize:CGSizeMake(2000, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
                    if (length > width-45*displaywidth)
                    {
                        length = width-45*displaywidth;
                    }
                    tasteBtn.frame = CGRectMake(15*displaywidth + w2, h2, length + 15*displaywidth , 25*displaywidth);
                    if(15*displaywidth + w2 + length + 15*displaywidth > width){
                        w2 = 0; //换行时将w置为0
                        h2 = h2 + tasteBtn.frame.size.height + 20*displaywidth;//距离父视图也变化
                        tasteBtn.frame = CGRectMake(15*displaywidth + w2, h2, length + 15*displaywidth, 25*displaywidth);//重设button的frame
                    }
                    w2 = tasteBtn.frame.size.width + tasteBtn.frame.origin.x+10*displaywidth;
                    
                    UIColor *bordercolor2 = BacksColor;
                    UIColor *titcolor2 = BlaTitColor;
                    [tasteBtn setTitleColor:titcolor2 forState:UIControlStateNormal];
                    tasteBtn.layer.cornerRadius = 12.5*displaywidth;
                    tasteBtn.layer.masksToBounds = YES;
                    tasteBtn.backgroundColor = bordercolor2;
                    [cell.contentView addSubview:tasteBtn];
                    
                }
                h2+=40*displaywidth;
                UIView *lineCview = [[UIView alloc] initWithFrame:CGRectMake(15*displaywidth, h2-1, SCREEN_WIDTH-30*displaywidth, 1)];
                lineCview.backgroundColor = LinesColor;
                [cell.contentView addSubview:lineCview];
            }
        }
        else
        {
            UIView *lineCview = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10*displaywidth)];
            lineCview.backgroundColor = BacksColor;
            [cell.contentView addSubview:lineCview];
            NSArray *titAry = @[@"工商认证",@"实地认证",@"资金保障"];
            NSString *gs = @"gsxy_icon01h";
            NSString *sd = @"gsxy_icon02h";
            NSString *zj = @"gsxy_icon03h";
            if (_detaModel.isGongShang)
            {
                gs = @"gsxy_icon01";
            }
            if ([_detaModel.shi integerValue] == 1)
            {
                sd = @"gsxy_icon02";
            }
            if ([_detaModel.bao integerValue] == 1)
            {
                zj = @"gsxy_icon03";
            }
            NSArray *imgAry = @[gs,sd,zj];
            NSArray *colorAry = @[RGB(20, 43, 126),RGB(252, 188, 1),RGB(51, 204, 153)];
            for (int i = 0; i < titAry.count; i++)
            {
                UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
                closebtn.frame = CGRectMake(SCREEN_WIDTH/3*i, 10*displaywidth, SCREEN_WIDTH/3, 80*displaywidth);
                [closebtn setImage:[UIImage imageNamed:imgAry[i]] forState:UIControlStateNormal];
                [closebtn setTitleColor:colorAry[i] forState:UIControlStateNormal];
                [closebtn setTitle:titAry[i] forState:UIControlStateNormal];
                closebtn.titleLabel.font = NormalFontWithSize(12.0+fontScale);
                closebtn.backgroundColor = [UIColor clearColor];
                closebtn.tag = 10+i;
                [closebtn addTarget:self action:@selector(itemBtnAction:) forControlEvents:UIControlEventTouchUpInside];
                [cell.contentView addSubview:closebtn];
                [self setButtonContentCenter:closebtn];
                if (i != 0)
                {
                    UIView *lineBview = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH/3*i, 27.5*displaywidth, 1, 45*displaywidth)];
                    lineBview.backgroundColor = RGB(204, 204, 204);
                    [cell.contentView addSubview:lineBview];
                }
            }
        }
    }
    else
    {
        if (_allcommentAry.count > 0)
        {
            CommentModel *model = _allcommentAry[indexPath.row];
            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(15*displaywidth, 15*displaywidth, 50*displaywidth, 50*displaywidth) ImageName:@"morenFace"];
            imgView.layer.cornerRadius = 25*displaywidth;
            imgView.layer.masksToBounds = YES;
            if (model.headImg.length > 0 && [model.isAnonymous integerValue] != 1)
            {
                [imgView sd_setImageWithURL:[NSURL URLWithString:model.headImg] placeholderImage:[UIImage imageNamed:@"morenFace"]];
            }
            [cell.contentView addSubview:imgView];
            NSString *name = model.username;
            if ([model.isAnonymous integerValue] == 1)
            {
                name = @"匿名用户";
            }
            UILabel *nameLab = [ZCControl createLabelWithFrame:CGRectMake(75*displaywidth, 15*displaywidth, SCREEN_WIDTH-170*displaywidth, 20*displaywidth) Font:15.0 Text:name Color:RGB(32, 69, 139)];
            [cell.contentView addSubview:nameLab];
            UILabel *timeLab = [ZCControl createLabelWithFrame:CGRectMake(SCREEN_WIDTH-95*displaywidth, 5*displaywidth, 80*displaywidth, 30*displaywidth) Font:10.0 Text:model.createDtm Color:RGB(185, 185, 185)];
            timeLab.numberOfLines = 0;
            timeLab.textAlignment = NSTextAlignmentRight;
            [cell.contentView addSubview:timeLab];
            UILabel *contenLab = [ZCControl createLabelWithFrame:CGRectMake(75*displaywidth, 35*displaywidth, SCREEN_WIDTH-120*displaywidth, 45*displaywidth) Font:12.0 Text:model.content Color:BlaTitColor];
            [cell.contentView addSubview:contenLab];
            UIView *lineEview = [[UIView alloc] initWithFrame:CGRectMake(0, 85*displaywidth, SCREEN_WIDTH, 10*displaywidth)];
            lineEview.backgroundColor = BacksColor;
            [cell.contentView addSubview:lineEview];
        }
        
    }
    
    return cell;
    
}

-(void)setButtonContentCenter:(UIButton *) btn
{
    CGSize imgViewSize,titleSize,btnSize;
    UIEdgeInsets imageViewEdge,titleEdge;
    CGFloat heightSpace = 10.0f;
    
    //设置按钮内边距
    imgViewSize = btn.imageView.bounds.size;
    titleSize = btn.titleLabel.bounds.size;
    btnSize = btn.bounds.size;
    
    imageViewEdge = UIEdgeInsetsMake(heightSpace,0.0, btnSize.height -imgViewSize.height - heightSpace, - titleSize.width);
    [btn setImageEdgeInsets:imageViewEdge];
    titleEdge = UIEdgeInsetsMake(imgViewSize.height +heightSpace, - imgViewSize.width, 0.0, 0.0);
    [btn setTitleEdgeInsets:titleEdge];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        if (indexPath.row == 0)
        {
            return 150*displaywidth;
        }
        else if (indexPath.row == 2)
        {
            CGFloat h2 = 10*displaywidth;
            CGFloat w2 = 0;
            CGFloat width = SCREEN_WIDTH;
            if (_typeAry.count > 0)
            {
                h2 = 25*displaywidth;
                for (int i = 0; i < _typeAry.count; i++)
                {
                    GoodsAddressModel *sizeModel = _typeAry[i];
                    NSString *typename = [NSString stringWithFormat:@"%@(%@)",sizeModel.name,sizeModel.count];
                    NSDictionary *attributes = @{NSFontAttributeName:NormalFontWithSize(12.0+fontScale)};
                    CGFloat length = [typename boundingRectWithSize:CGSizeMake(2000, 25*displaywidth) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size.width;
                    if (length > width-45*displaywidth)
                    {
                        length = width-45*displaywidth;
                    }
                    if(15*displaywidth + w2 + length + 15*displaywidth > width){
                        w2 = 0; //换行时将w置为0
                        h2 = h2 + 25 + 20*displaywidth;//距离父视图也变化
                    }
                    w2 = length + 15*displaywidth + 15*displaywidth + w2;
                }
                h2+=40*displaywidth;
            }
            
            return h2;
        }
        return 90*displaywidth;
    }
    
    return 95*displaywidth;
}


- (void)itemBtnAction:(UIButton *)btn
{
    if (btn.tag == 10 && _detaModel.isGongShang)
    {
        IndustrialViewController *vc = [[IndustrialViewController alloc] init];
        vc.model = _detaModel;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


//我要评论
- (void)soureBtnAction
{
    UserAccountModel *userModel = [UserAccountModel shareMange];
    if (![LTools storageForKey:SERVER_IsLogin])
    {
        [LTools showMBProgressWithText:@"请先登录" addToView:self.view];
        return;
    }
    if (userModel.isIdentify != 1)
    {
        [LTools showMBProgressWithText:@"请先实名认证" addToView:self.view];
        return;
    }
    CommentOfMineViewController *vc = [[CommentOfMineViewController alloc] init];
    vc.detaModel = _detaModel;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)requestComment
{
    WEAKSELF;
    NSDictionary *dic = @{@"joinId":_comPanyId,
                          @"type":@"1"
                          };
    [HYBaseHandler requestWithTheFormUrl:SERVER_commentType Parmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _typeAry = [GoodsAddressModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

//公司详情
- (void)requestCompanySelect
{
    WEAKSELF;
    NSDictionary *dic = @{@"id":_comPanyId};
    [HYBaseHandler requestCompanySelectParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _detaModel = [DetailsModel mj_objectWithKeyValues:obj[@"data"]];
            if ([obj[@"data"][@"companyInfo"] isKindOfClass:[NSDictionary class]])
            {
                _detaModel.isGongShang = YES;
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}

- (void)requestCommentList
{
    WEAKSELF;
    NSDictionary *dic = @{@"joinId":_comPanyId,
                          @"type":@"1",
                          @"page":s_Integer(_page),
                          @"size":@"15"
                          };

    [HYBaseHandler requestWithTheFormUrl:SERVER_commentList Parmers:dic Success:^(id obj) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
        if ([obj server_Getcodecheck])
        {
            NSArray *comAry = [CommentModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (_page == 0)
                {
                    [weakSelf.allcommentAry removeAllObjects];
                }
                [weakSelf.allcommentAry addObjectsFromArray:comAry];
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        [weakSelf.tableview.mj_header endRefreshing];
        [weakSelf.tableview.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
